<?php
/***************************************************************************
 *   Copyright (C) 2010 by Math2Gold,Twitter @math2gold                    *
 *   math2gold#gmail.com                                                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

require_once('io43_simpletalk_core.php');

ini_set( "php-gtk.codepage" , "UTF-8");

class bbpress_login_set
{
    public $st_load;
    public $st_send;
    public $conf;

    function __construct($url,$username,$password)
    {
        $this->st_load=new fandong_simple_talk();
        $conf=$this->st_load->get_config_by_url($url);
        if ($conf==NULL) throw new Exception("Load conf error");
        $this->st_load->config($conf);
        $this->st_load->loginparam->uname=$username;
        $this->st_load->loginparam->pwd=$password;
        $this->ret=$this->st_load->login();
        $this->st_send=new fandong_simple_talk();
        $this->st_send->config($conf);
        $this->st_send->loginparam->uname=$username;
        $this->st_send->loginparam->pwd=$password;
        $this->conf=$conf;
    }

    function check_login()
    {
        return $this->ret;
    }
}

class gui_runner
{
    public $window;
    public $timeout;
    public $view;
    public $taglist;
    public $buffer;
    public $show_front;

    function set_window_state()
    {
        $this->window->connect_simple('destroy', array('gtk', 'main_quit'));
        $this->window->set_title('[simple chat] http://fandong.org/ ');
        $this->window->set_size_request(600,440);
        $this->window->set_position(Gtk::WIN_POS_CENTER);
        $this->window->set_border_width(8);
    }

    function set_hooks()
    {
        $this->btnSend->connect_simple('clicked', 'send', $this->viewtosend,$this);
        $this->btnUpload->connect_simple('clicked', 'choose_file',
                                         $this->window,$this
                                        );
        $this->window->connect_simple('size-allocate','force_size',$this);
        $this->viewtosend->connect('key-press-event', 'send_msg_by_key',$this);
        Gtk::timeout_add($this->time_out, 'dial_timeout',$this);
    }

    function set_layout()
    {
        $this->window->add($this->vbox = new GtkVBox());

        $this->view->set_buffer($this->buffer);
        $this->view->modify_font(new PangoFontDescription($this->show_front));
        $this->view->set_wrap_mode(Gtk::WRAP_WORD);
        $this->view->set_editable(false);
        $this->view->set_size_request(600,332);

        $this->scwnd->set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
        $this->scwnd->add($this->view);

        $this->usrctr=new GtkHBox();

        $this->vbox->pack_start($this->scwnd);
        $this->vbox->pack_start($this->usrctr);


        $this->buttonlist=new GtkVBox();

        $this->usrctr->add($this->viewtosend);
        $this->usrctr->add($this->buttonlist);

        $this->buttonlist->add($this->btnUpload);
        $this->buttonlist->add($this->btnSend);

        $this->viewtosend->grab_focus();
        $this->viewtosend->set_editable(true);
        $this->viewtosend->set_size_request(480,80);

        $this->btnSend->set_size_request(60,28);
        $this->btnUpload->set_size_request(60,28);
    }

    function get_chat_window()
    {
        $this->time_out=3000;

        $this->window = new GtkWindow();
        $this->set_window_state();

        $this->scwnd     = new GtkScrolledWindow();

        $this->buffer    = new GtkTextBuffer();
        $this->view      = new GtkTextView();
        $this->viewtosend= new GtkTextView();
        $this->btnSend   = new GtkButton('_Send');
        $this->btnUpload = new GtkButton('_Upload');
        $this->set_layout();

        $this->set_hooks();

        $this->taglist=$this->get_styles();
        $this->window->show_all();
        return $this->window;
    }


    function get_styles()
    {
        $taglist=array();

        $tag=new GtkTextTag();
        $tag->set_property('weight',Pango::WEIGHT_BOLD);
        $this->buffer->get_tag_table()->add($tag);
        $taglist["B"]=$tag;

        $tag=new GtkTextTag();
        $tag->set_property('style',Pango::STYLE_ITALIC);
        $this->buffer->get_tag_table()->add($tag);
        $taglist["I"]=$tag;
        return $taglist;
    }

    function get_pixbuf_by_url($url,$api,$sch='/^http\:\/\/api\.fandong\.org\/get_file.php\?id\=([0-9]*)\&hash\=([0-9a-z]{40})$/',$sch_ord=2)
    {
        $p=$sch;
        preg_match($p,$url,$matches);
        $hash=($matches[$sch_ord]);
        $cache='./temp.img/'.$hash;
        if (!file_exists($cache))
        {
            $api->load_data($url);
            if ($api->http_code==200)
            {
                file_put_contents($cache,$api->response);
            }
            else return NULL;
        }
        $g=getimagesize($cache);
        if (empty($g))
        {
            unlink($cache);
            return NULL;
        }
        $img=GdkPixbuf::new_from_file($cache);
        return $img;
    }
}

function force_size($top)
{
    $g=$top->window->get_size();
    $inb=$top->vbox->get_allocation();
    $top->view->set_size_request(-1,intval($inb->height)-60);
    $top->viewtosend->set_size_request($g[0]-60,60);
    $top->usrctr->set_size_request($g[0]-60,60);
    $top->btnSend->set_size_request(60,28);
    $top->btnUpload->set_size_request(60,28);

}

function choose_file(GtkWindow $wnd,$top)
{
    $dialog = new GtkFileChooserDialog("File Open", null,
                                       Gtk::FILE_CHOOSER_ACTION_OPEN,
                                       array(Gtk::STOCK_OK, Gtk::RESPONSE_OK), null); // note 2
    $dialog->show_all();
    if ($dialog->run() == Gtk::RESPONSE_OK)
    {
        $selected_file = $dialog->get_filename();
        $top->opset->st_send->send_img($selected_file);
    }
    $dialog->destroy();
}
function dial_timeout($top)
{

    $r=$top->opset->st_load->recv();
    if ($r)
    {
        $insert=$top->buffer->get_end_iter();
        $j=count($r);
        for ($i=$j-1;$i>=0;$i--)
        {
            $p=$r[$i];
            $msg=$p->{'msg'};
            $sender=$p->{'sender'};
            $ctime=$p->{'time'};

            $top->buffer->insert($insert,$sender);
            $top->buffer->apply_tag(
                $top->taglist["B"],
                $top->buffer->get_iter_at_line_offset($top->buffer->get_line_count(),0),
                $insert);
            $mark=$top->buffer->create_mark(NULL,$insert,true);
            $top->buffer->insert($insert,"(".$ctime.")");
            $top->buffer->apply_tag(
                $top->taglist["I"],
                $top->buffer->get_iter_at_mark($mark),
                $insert);
            $top->buffer->delete_mark($mark);

            switch (intval($p->{'type'}))
            {
            case 1:
                $top->buffer->insert($insert,":");
                $top->buffer->insert_pixbuf($insert,
                                            $top->get_pixbuf_by_url($msg,
                                                                    $top->opset->st_load->core(),
                                                                    $top->opset->conf->recvimg->regex,
                                                                    $top->opset->conf->recvimg->match
                                                                   )
                                           );
                $top->buffer->insert($insert,"\n");
                break;
            default:
                $top->buffer->insert($insert,":".$msg."\n");
            }

            $mark=$top->buffer->create_mark(NULL,$insert,true);
            $top->view->scroll_mark_onscreen($mark);
            $top->buffer->delete_mark($mark);

        }
    }

    Gtk::timeout_add($top->time_out, 'dial_timeout',$top);
}

function send(GtkTextView $viewtosend,$top)
{
    $buffer=$viewtosend->get_buffer();
    $text=$buffer->get_text($buffer->get_start_iter(),$buffer->get_end_iter());
    if ($text=='') return;
    $r=$top->opset->st_send->send($text);
    $buffer->set_text('');
}


function send_msg_by_key($widget, $event ,$top)
{
    if ( ($event->state & Gdk::CONTROL_MASK) &&

            ($event->keyval == Gdk::KEY_KP_Enter
             ||
             $event->keyval == Gdk::KEY_ISO_Enter
             ||
             $event->keyval == Gdk::KEY_Return
             ||
             $event->keyval == Gdk::KEY_Execute
             ||
             $event->keyval == Gdk::KEY_3270_Enter
            )

       )
    {
        send($top->viewtosend,$top);
    }
}

